import logging

from flask import Blueprint, request
from flask import jsonify

from airflow.patsnap.service import auth_service
from airflow.www.api import provide_user, exception_handle

log = logging.getLogger(__name__)

api_speech_auth = Blueprint('api_speech_auth', __name__)


# user route
@api_speech_auth.route('/auth/is_path_auth', methods=['GET'])
@exception_handle
@provide_user
def is_path_auth(oa_user_name):
    path = request.values.get("path", type=str, default=None)
    if path is None:
        log.error("is_path_auth params error path={%s}", path)
        return jsonify(code=500, message="is_path_auth params has None,", data=None)

    have_path = auth_service.is_path_auth(path, oa_user_name)
    if have_path:
        return jsonify(code=0, message='ok', data=have_path)
    else:
        return jsonify(code=403, message='no Permission', data=have_path)


@api_speech_auth.route('/auth/apply_token/', methods=['GET'])
@exception_handle
def auth_apply_tokens():
    oa_user_name = request.args.get("username", type=str, default=None)
    if oa_user_name is None:
        log.error("apply_token params error username={%s}", oa_user_name)
        return jsonify(code=400, message="applyToken params has None,", data=None)

    result = auth_service.apply_token(oa_user_name)
    return jsonify(code=0, message='ok', data=result)


@api_speech_auth.route('/auth/login', methods=['POST'])
@exception_handle
def login():
    user = request.json
    username = user['username']
    password = user['password']
    if username is None or password is None:
        log.error("login params error username={%s},password={%s}", username, password)
        return jsonify(code=400, message="login params has None,", data=None)

    result = auth_service.login(username, password)
    if result:
        return jsonify(code=0, message='ok', data=result)
    else:
        return jsonify(code=401, message='ok', data=result)

